package com.project.music.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.project.music.bean.Consumer;
import com.project.music.service.ConsumerService;
import com.project.music.utils.Consts;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 用户控制类
 */

@Api(tags = "用户控制类")
@RestController
@RequestMapping("/user")
public class ConsumerController {

    @Autowired
    private ConsumerService consumerService;

    //返回所有用户
    @ApiOperation("返回所有用户")
    @GetMapping("")
    public List<Consumer> allUser() {
        return consumerService.list();
    }
    //返回指定ID的用户
    @ApiOperation("返回指定ID的用户")
    @GetMapping("/detail")
    public Consumer userOfId(@RequestParam("id") @ApiParam("用户ID") int id) {
        return consumerService.getById(id);
    }
    //添加用户
    @ApiOperation("添加用户")
    @PostMapping("/add")
    public JSONObject addUser(Consumer consumer) {
        JSONObject jsonObject = new JSONObject();

        if (consumer.getUsername().equals("") || consumer.getUsername()==null) {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "用户名或密码错误");
            return jsonObject;
        }
        if (consumer.getPhoneNum().equals("")) {
            consumer.setPhoneNum(null);
        }
        if (consumer.getEmail().equals("")) {
            consumer.setEmail(null);
        }

        consumer.setCreateTime(new Date());
        consumer.setUpdateTime(new Date());

        boolean status = consumerService.save(consumer);
        if (status) {
            jsonObject.put(Consts.CODE, 1);
            jsonObject.put(Consts.MSG, "注册成功");
        } else {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "注册失败");
        }
        return jsonObject;
    }
    //判断是否登录成功
    @ApiOperation("判断是否登录成功")
    @PostMapping("/login/status")
    public JSONObject loginStatus(@RequestParam("username") @ApiParam("用户名") String username,
                              @RequestParam("password") @ApiParam("密码") String password,
                              HttpSession session) {
        JSONObject jsonObject = new JSONObject();

        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                    .eq(Consumer::getUsername, username)
                    .eq(Consumer::getPassword, password);
        List<Consumer> consumerList = consumerService.list(queryWrapper);
        boolean status = consumerList.size() > 0;
        if (status){
            jsonObject.put(Consts.CODE, 1);
            jsonObject.put(Consts.MSG, "登录成功");
            jsonObject.put("userMsg", consumerList);
            session.setAttribute("username", username);
        }else {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "用户名或密码错误");
        }
        return jsonObject;
    }
    //删除用户
    @ApiOperation("删除用户")
    @GetMapping("/delete")
    public Boolean deleteUser(@RequestParam("id") @ApiParam("用户ID") int id) {
        Consumer consumer = consumerService.getById(id);
        if (!consumer.getAvator().equals("/img/user.jpg")) {
            String picPath = Consts.ROOT + consumer.getAvator();
            File picFile = new File(picPath);
            return consumerService.removeById(id) && picFile.delete();
        } else {
            return consumerService.removeById(id);
        }
    }
    //更新用户信息
    @ApiOperation("更新用户信息")
    @PostMapping("/update")
    public JSONObject updateUserMsg(Consumer consumer) {
        JSONObject jsonObject = new JSONObject();

        if (consumer.getUsername().equals("") || consumer.getUsername()==null) {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "用户名或密码错误");
            return jsonObject;
        }
        if (consumer.getPhoneNum().equals("")) {
            consumer.setPhoneNum(null);
        }
        if (consumer.getEmail().equals("")) {
            consumer.setEmail(null);
        }

        consumer.setUpdateTime(new Date());

        boolean status = consumerService.updateById(consumer);
        if (status) {
            jsonObject.put(Consts.CODE, 1);
            jsonObject.put(Consts.MSG, "修改成功");
        } else {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "修改失败");
        }
        return jsonObject;
    }
    //更新用户头像
    @ApiOperation("更新用户头像")
    @PostMapping("/avatar/update")
    public JSONObject updateUserPic(@RequestParam("file") @ApiParam("头像文件") MultipartFile avatarFile,
                                @RequestParam("id") @ApiParam("用户ID") int id) {
        JSONObject jsonObject = new JSONObject();

        if (avatarFile.isEmpty()) {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "文件上传失败！");
            return jsonObject;
        }
        String fileName = System.currentTimeMillis() + avatarFile.getOriginalFilename();
        String filePath = Consts.ROOT + Consts.SEPARATOR + "avatorImages";

        File path = new File(filePath);
        if (!path.exists()) {
            path.mkdir();
        }

        File dest = new File(filePath + Consts.SEPARATOR + fileName);
        String storeAvatarPath = "/avatorImages/"+fileName;
        try {
            avatarFile.transferTo(dest);
            UpdateWrapper<Consumer> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda()
                    .eq(Consumer::getId, id)
                    .set(Consumer::getAvator, storeAvatarPath);
            boolean status = consumerService.update(updateWrapper);
            if (status) {
                jsonObject.put(Consts.CODE, 1);
                jsonObject.put(Consts.MSG, "上传成功");
            }
            else {
                jsonObject.put(Consts.CODE, 0);
                jsonObject.put(Consts.MSG, "上传失败");
            }
            return jsonObject;
        } catch (IOException e) {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "上传失败" + e.getMessage());
            return jsonObject;
        }
    }
}
